<template>
    <view class="page_main">
        <HeaderBar :navBarBgc="headerBgc"></HeaderBar>
        <view class="container">
            <!-- 搜索栏 -->
            <view class="header">
                <view class="search">
                    <wd-input type="text" v-model="searchValue" clearable no-border placeholder="搜索订单" @change="handleChange" />
                    <button class="search_btn" @click="handSearch"><uni-icons type="search" color="#fff" size="24"></uni-icons></button>
                </view>
            </view>
            <!-- 标签页 -->
            <wd-tabs v-model="tab" slidable="always" @change="handleTabChange">
                <block v-for="(item, index ) in tabList" :key="index">
                    <wd-tab :name="index" :title="item.label">
                        <!-- <view class="content">内容{{ item }}</view> -->
                    </wd-tab>
                </block>
            </wd-tabs>
            <!-- 订单列表 -->
            <scroll-view scroll-y="true" class="scroll-Y">
				<view class="order_list">
                    <view class="order_item" v-for="(item,index) in orderList" :key="index" @click="toOrderDetail(item.id)">
                        <view class="item_header">
                            <view class="title">
                                <view class="name">{{ item.thaliName }}</view>
                                <view class="order_id">订单编号：{{ item.id }}</view>    
                            </view>
                            <view class="status_time">
                                <view class="status" v-if="item.status === 1">待付款</view>
                                <view class="status" v-if="item.status === 2">待确认</view>
                                <view class="status" v-if="item.status === 3">待使用</view>
                                <view class="status" v-if="item.status === 4">已完成</view>
                                <view class="time" v-if="item.status === 1">剩余时间：<wd-count-down :time="item.remainingTime || 0" format="mm:ss"  /></view>
                            </view>
                        </view>
                        <view class="item_body">
                            <img class="img" src="" alt="">
                            <view class="info">
                                <view class="text">
                                    <view class="info_name">{{item.thaliName}}</view>
                                    <view class="intro">{{item.thaliMemo}}</view>
                                    <view class="intro">使用时间：{{item.useDate}}</view>
                                    <view class="num">数量：{{item.number}}张</view>
                                </view>
                                <view class="price">￥<text class="price_num">{{item.payAmount.toFixed(2)}}</text></view>
                            </view>
                        </view>
                        <view class="btns">
                            <button class="btn" v-if="item.status === 1">取消订单</button>
                            <button class="btn btn_c" v-if="item.status === 1">立即付款</button>
                            <button class="btn" v-if="item.status === 4">申请开票</button>
                            <button class="btn" v-if="item.status === 4">申请售后</button>
                            <button class="btn btn_c" v-if="item.status === 4">再次购买</button>
                            <button class="btn btn_c" v-if="item.status === 3">申请退款</button>
                        </view>
                    </view>
                    <wd-status-tip v-if="!orderList.length" image="search" tip="暂无数据" />
                    <view class="more" @click="loadMore" v-if="hasMore">
                            查看更多
                        <wd-icon name="arrow-down"></wd-icon>
                    </view>
                    <view class="more" v-else>
                        没有更多了~
                    </view>
                </view>
			</scroll-view>
        </view>
    </view>
</template>

<script lang="ts" setup>
import HeaderBar from "@/components/HeaderBar/index.vue";
import { orderListApi } from "@/api/common"
import { ref, onMounted , computed, reactive } from 'vue'
import { Value } from "sass";

const headerBgc = ref("linear-gradient(to bottom, #1b9c61, #ffffff)");
const searchValue =ref('')
interface TabItem {
  label: string
  key: number // 后端枚举值
}

// 原始数据保持与后端一致
const tabList = ref<TabItem[]>([
  { label: '全部订单', key: 0 },
  { label: '待付款', key: 1 },
  { label: '待确认/发货', key: 2 },
  { label: '待使用/收货', key: 3 },
  { label: '退款/售后', key: 4 }
])
const tab = ref<number>(0) // 默认选中全部订单
// 分页查询参数
const pageQuery = ref({
	pageNo: 1,
	pageSize: 10
});
  
// 产品筛选条件
const productFilters = ref({
    keyWord:'',
    status:0,
});
// 封装请求参数
  const params = computed(() => ({
	...productFilters.value,
	pageNo: pageQuery.value.pageNo,
	pageSize: pageQuery.value.pageSize
}));
// const orderList = ref([]);
const hasMore =ref(true)

// 修改订单类型定义
interface OrderItem {
    // 其他原有字段...
    createTime: string
    remainingTime?: number
}

const orderList = ref<OrderItem[]>([]);
let timer: number

// 计算剩余时间方法
const calculateRemaining = (createTime: string): number => {
  // 修复时间格式，确保兼容性（如将空格替换为'T'，添加时区）
  const isoTime = createTime.replace(' ', 'T') + 'Z' // 假设后端返回的是UTC时间
  const createTimestamp = new Date(isoTime).getTime()
  
  // 验证时间戳有效性
  if (isNaN(createTimestamp)) {
    console.error('Invalid createTime:', createTime)
    return 0
  }

  const endTimestamp = createTimestamp + 15 * 60 * 1000
  const now = Date.now()
  return Math.max(endTimestamp - now, 0)
}
// 初始化订单倒计时
const initOrderTimers = () => {
    orderList.value = orderList.value.map(order => {
        if (order.status === 1) {
            return {
                ...order,
                remainingTime: calculateRemaining(order.createTime)
            }
        }
        // 非待付款订单移除倒计时字段
        const { remainingTime, ...rest } = order
        return rest
    })
}
// 更新倒计时
const updateTimers = () => {
    orderList.value = orderList.value.map(order => {
        if (order.status === 1 && order.remainingTime) {
            const newTime = order.remainingTime - 1000
            return {
                ...order,
                remainingTime: newTime > 0 ? newTime : 0
            }
        }
        return order
    })
}
onMounted(()=>{
    getOrderList()
})
// const getOrderList =()=>{
//     orderListApi().then((res)=>{
//         console.log('.......777',res);
        
//     })
// }
 const getOrderList = async () => {
	try {
	  const {result} = await orderListApi(params.value);
      console.log( '----res',result);
      
	  if (result.length > 0) {
		orderList.value = [...orderList.value, ...result]; // 优化性能
		pageQuery.value.pageNo++;
        initOrderTimers() // 初始化倒计时
        startCountdown()  // 启动定时器
	  }
	  if (result.length < pageQuery.value.pageSize) {
		hasMore.value = false;
	  }
	} catch (error) {
	  console.error("接口调用失败：", error);
	}
  };
const handleTabChange = (val) => {
    // 通过索引获取对应的业务 key
    productFilters.value.status = tabList.value[val.name].key;
    orderList.value = [];
    pageQuery.value.pageNo = 1;
    getOrderList()
}
const handleChange =(event)=>{
    console.log('.....',event);
    
}
const handSearch =()=>{
    productFilters.value.keyWord = searchValue.value;
    orderList.value = [];
    getOrderList()
    
}
const loadMore =()=>{
    console.log('查看更多',);
    getOrderList()
}
const toOrderDetail =(id)=>{
     uni.navigateTo({
        url: `/premiumRouteSubPack/pages/orderDetails/index?id=${id}`
    });
}
//启动倒计时
const startCountdown = () => {
    stopCountdown()
    timer = setInterval(updateTimers, 1000)
}

// 停止倒计时
const stopCountdown = () => {
    if (timer) clearInterval(timer)
}

onBeforeUnmount(() => {
    stopCountdown()
})
</script>

<style lang="scss" scoped>
.page_main{
    height: 100vh;
    background: #eeefe7;
    .container{
        .header{
            padding: 44rpx 28rpx 0;
            background: #fff;
            .search{
                display: flex;
                align-items: center;
                height: 70rpx;
                border: 2rpx solid #1B9C61;
                border-radius: 35rpx;
                padding-left: 35rpx;
                :deep(.wd-input){
                    flex: 1;
                    margin-right: 20rpx;
                }
                :deep(.is-not-empty){
                    
                }
                .search_btn{
                    margin: 0;
                    width: 125rpx;
                    height: 70rpx;
                    line-height: 70rpx;
                    background: #1B9C61;
                    border-radius: 35rpx;
                }
            }
        }
        :deep(.wd-tabs){
            padding: 20rpx 0;
            .wd-tabs__nav-item{
                padding: 0 28rpx;
            }
            .wd-tabs__line{
                width: 10%;
                background: #1B9C61;
            }
        }
        .scroll-Y{
            padding: 28rpx;
            box-sizing: border-box;
            height: 1200rpx;
        }
        .order_list{
            .order_item{
                background: #fff;
                border-radius: 10rpx;
                padding: 30rpx 27rpx 27rpx;
                margin-bottom: 27rpx;
                .item_header{
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    .title{
                        .name{
                            font-size: 29rpx;
                            font-weight: bold;
                        }
                        .order_id{
                            margin-top: 15rpx;
                            display: flex;
                            align-items: center;
                            font-size: 25rpx;
                            color: #777777;
                        }
                    }
                    .status_time{
                        text-align: right;
                        font-size: 25rpx;
                        color: #AA5413 ;
                        .status{}
                        .finish{
                            color: #777;
                        }
                        .time{
                            display: flex;
                            align-items: center;
                        }
                        :deep(.wd-count-down){
                            color: #AA5413;
                        }
                    }
                }
                .item_body{
                    margin-top: 13rpx;
                    padding: 27rpx 0;
                    display: flex;
                    align-items: center;
                    border-top: 1px solid #EEF0DF;
                    .img{
                        width: 125rpx;
                        height: 125rpx;
                        margin-right: 26rpx;
                        border-radius: 10rpx;
                    }
                    .info{
                        flex: 1;
                        display: flex;
                        justify-content: space-between;
                        .text{
                            .info_name{
                                font-size: 25rpx;
                                font-weight: bold;
                                margin-bottom: 8rpx;
                            }
                            .intro{
                                font-size: 22rpx;
                                color: #777;
                            }
                            .num{
                                font-size: 22rpx;
                                margin-top: 8rpx;
                            }
                        }
                        .price{
                            font-size: 22rpx;
                            .price_num{
                                font-size: 28rpx;
                            }
                        }
                    }
                }
                .btns{
                    display: flex;
                    justify-content: flex-end;
                    align-items: center;
                    .btn{
                        width: 138rpx;
                        height: 41rpx;
                        border-radius: 10rpx;
                        margin: 0;
                        font-size: 25rpx;
                        background: #EEF0DF;
                        padding: 0;
                        text-align: center;
                        line-height: 41rpx;
                        margin-left: 18rpx;
                    }
                    .btn_c{
                        color: #fff;
                        background: #1B9C61;
                    }
                }
            }
            .more{
                font-size: 25rpx;
                text-align: center;
                color: #777;
            }
        }
    }
}
</style>